use serde::{Deserialize, Serialize};
use crate::config::run_setup::RUN_SETUP_CONFIG;
use crate::util::path_helper::get_is_exists;
use crate::util::path_helper::create_dir_all;
use crate::util::yaml_helper::write_yaml_file;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SiteBaseConfig {
  pub site_name: String,
  pub url_origin: String,
}

impl SiteBaseConfig {  
  pub fn get_site_directory(&self) -> String {
    format!("{}/site-{}", RUN_SETUP_CONFIG.log_root, self.site_name)
  }

  pub fn get_cache_site_directory(&self) -> String {
    format!("{}/site-{}", RUN_SETUP_CONFIG.log_cache, self.site_name)
  }

  pub fn get_site_info_file(&self) -> String {
    format!("{}/site-base.yml", self.get_site_directory())
  }

  pub fn get_site_apps_directory(&self) -> String {
    format!("{}/apps", self.get_site_directory())
  }
  
  pub fn make_site_directory(&self) -> bool {
    let site_directory = self.get_site_directory();
    let target_dir_path = site_directory.as_str();
    let result_is_exist = get_is_exists(target_dir_path);
    if result_is_exist.is_exist() {
      return true;
    }
    if result_is_exist.is_not_exist() {
      let is_success = create_dir_all(target_dir_path); 
      if !is_success {
        return false;
      }
      let apps_dir = self.get_site_apps_directory();
      return create_dir_all(apps_dir.as_str());
    }
    return false;
  }

  pub fn write_site_info_file(&self) -> bool {
    let site_info_file_string = self.get_site_info_file();
    let site_info_file = site_info_file_string.as_str();
    let result_is_exist = get_is_exists(site_info_file);
    if result_is_exist.is_exist() {
      return true;
    }    
    if result_is_exist.is_not_exist() {
      let mkdir_result = self.make_site_directory();
      if !mkdir_result {
        return false;
      }
      write_yaml_file(site_info_file, self);
      return true;
    }
    return false;
  }
}
